package com.ruoyi.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.base.domain.BaseLottery;
import com.ruoyi.base.domain.vo.LotteryVo;
import com.ruoyi.base.service.IBaseLotteryService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.sale.domain.SaleLotteryOne;
import com.ruoyi.sale.domain.SaleLotterySix;
import com.ruoyi.sale.domain.SaleLotteryThree;
import com.ruoyi.sale.service.ISaleLotteryOneService;
import com.ruoyi.sale.service.ISaleLotterySixService;
import com.ruoyi.sale.service.ISaleLotteryThreeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

/**
 * 彩票基础数据Controller
 *
 * @author szm
 * @date 2025-09-23
 */
@Slf4j
@Api(tags = "彩票基础数据接口")
@RestController
@RequestMapping("/base/BaseLottery")
public class BaseLotteryController extends BaseController {
    @Autowired
    private IBaseLotteryService baseLotteryService;

    @Autowired
    private ISaleLotteryOneService oneService;

    @Autowired
    private ISaleLotterySixService sixService;

    @Autowired
    private ISaleLotteryThreeService threeService;

    /**
     * 查询彩票基础数据列表
     */
    @ApiOperation("查询彩票基础数据列表")
    @GetMapping("/list")
    public TableDataInfo list(BaseLottery baseLottery) {
        startPage();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(baseLottery);
        queryWrapper.orderByDesc("buy_no");
        List<BaseLottery> list = baseLotteryService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出彩票基础数据列表
     */
    @ApiOperation("导出彩票基础数据列表")
    @Log(title = "彩票基础数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BaseLottery baseLottery) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(baseLottery);

        List<BaseLottery> list = baseLotteryService.list(queryWrapper);
        ExcelUtil<BaseLottery> util = new ExcelUtil<BaseLottery>(BaseLottery.class);
        util.exportExcel(response, list, "彩票基础数据数据");
    }

    /**
     * 获取彩票基础数据详细信息
     */
    @ApiOperation("获取彩票基础数据详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getById(@PathVariable("id") String id) {
        return success(baseLotteryService.getById(id));
    }

    /**
     * 新增彩票基础数据
     */
    @ApiOperation("新增彩票基础数据")
    @Log(title = "彩票基础数据", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody BaseLottery baseLottery) {
        return toAjax(baseLotteryService.saveOrUpdate(baseLottery));
    }

    /**
     * 修改彩票基础数据
     */
    @ApiOperation("修改彩票基础数据")
    @Log(title = "彩票基础数据", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResult edit(@RequestBody BaseLottery baseLottery) {

        BigDecimal decimal = new BigDecimal(baseLottery.getMaxBuyNo());

        if (baseLottery.getBuyNo().compareTo(decimal) <= 0) {
            return toAjax(baseLotteryService.updateById(baseLottery));
        } else {
            return AjaxResult.error("购买数量大于最大设置数量，请重新输入!");
        }
    }

    /**
     * 删除彩票基础数据
     */
    @ApiOperation("删除彩票基础数据")
    @Log(title = "彩票基础数据", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(baseLotteryService.removeById(ids));
    }


    /**
     * 彩票购买新增
     */
    @ApiOperation("彩票购买")
    @PostMapping("/buyLotter")
    public AjaxResult buyLotter(@RequestBody LotteryVo lotter) {
        List<LotteryVo> b = baseLotteryService.buyLotter(lotter);
        return AjaxResult.success(b);
    }

    /**
     * 彩票购买新增
     */
    @ApiOperation("彩票购买2")
    @PostMapping("/buyLotter2")
    public AjaxResult buyLotter2(@RequestBody LotteryVo lotter) {

        try {

            String path = baseLotteryService.buyLotter2(lotter);

            log.info("文件地址：" + path);
            if (StringUtils.isNotEmpty(path)) {
                Path filePath = Paths.get(path);

                if (!Files.exists(filePath) || Files.isDirectory(filePath)) {
                    return AjaxResult.error();
                }

                byte[] pdfContent = Files.readAllBytes(filePath);

                log.info("文件流：" + pdfContent.toString());

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_PDF);
                headers.setContentDisposition(
                        ContentDisposition.inline().filename(getFileName(path)).build()
                );
                headers.setContentLength(pdfContent.length);

                ResponseEntity responseEntity = new ResponseEntity(pdfContent, headers, HttpStatus.OK);

                return AjaxResult.success(responseEntity);

                /*Resource resource = new UrlResource(filePath.toUri());
                if (!resource.exists()) {
                    return ResponseEntity.notFound().build();
                }*/

                // 获取文件类型
               /* String contentType = Files.probeContentType(filePath);
                if (contentType == null) {
                    contentType = "application/octet-stream";
                }

                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(contentType))
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename=\"" + bytes.getFilename() + "\"")
                        .body(bytes);*/
            }

        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.success();
        }
        return AjaxResult.success();
    }

    @ApiOperation("一键设置最大购买数量")
    @PostMapping("/updateAll")
    public AjaxResult updateAll(@RequestParam("maxBuyNo") Integer maxBuyNo, @RequestParam("lotteryType") String lotteryType) {
        int b = baseLotteryService.updateAll(maxBuyNo, lotteryType);
        return AjaxResult.success(b);
    }

    /**
     * @param lotteryNo
     * @return
     */
    @ApiOperation("根据彩票号获取单选售卖记录")
    @GetMapping(value = "/getByLottNo")
    public AjaxResult getByLottNo(@RequestParam("lotteryNo") String lotteryNo,
                                  @RequestParam("lotteryType") String lotteryType) {


        if (lotteryType.equals("1")) {
            List<SaleLotteryOne> list = oneService.lambdaQuery()
                    .eq(SaleLotteryOne::getLotteryNo, lotteryNo).list();
            return success(list);
        } else if (lotteryType.equals("2")) {
            List<SaleLotteryThree> list = threeService.lambdaQuery()
                    .eq(SaleLotteryThree::getLotteryNo, lotteryNo).list();
            return success(list);
        } else if (lotteryType.equals("3")) {
            List<SaleLotterySix> list = sixService.lambdaQuery()
                    .eq(SaleLotterySix::getLotteryNo, lotteryNo).list();
            return success(list);
        }
        return success();
    }

    @ApiOperation("随机获取注码")
    @GetMapping("/getSampleData")
    public AjaxResult getSampleData(@RequestParam("sampleSize") Integer sampleSize) {
        List<BaseLottery> lotteryList = baseLotteryService.lambdaQuery().eq(BaseLottery::getLotteryType, 1).list();
        List<String> originalList = lotteryList.stream().map(BaseLottery::getLotteryNo).collect(Collectors.toList());
        // 创建列表的副本以避免修改原列表
        List<String> copyList = new ArrayList<>(originalList);

        // 随机打乱列表
        Collections.shuffle(copyList);

        // 返回前N个元素
        List<String> list = copyList.subList(0, sampleSize);
        Collections.sort(list);
        String result = String.join(" ", list);

        return AjaxResult.success("获取成功",result);
    }

    @ApiOperation("获取上一张票")
    @GetMapping("/getLastLotter")
    public AjaxResult getLastLotter() {
        LotteryVo lastLotter = baseLotteryService.getLastLotter();
        return AjaxResult.success("获取成功",lastLotter);
    }

    private String getFileName(String filePath) {
        return filePath.substring(filePath.lastIndexOf("\\") + 1);
    }
}
